package com.zlm.weather.controller;

import com.alibaba.fastjson.JSON;
import com.zlm.weather.pojo.City;
import com.zlm.weather.pojo.Province;
import com.zlm.weather.pojo.WeatherResponse;
import com.zlm.weather.service.CityService;
import com.zlm.weather.service.WeatherService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author: 郑
 * @Date: Create in 2020-1-18.
 */
@Controller
@RequestMapping("/city")
public class CityController {

    @Autowired
    private CityService cityService;
    @Autowired
    private WeatherService weatherService;

    //首页
    @GetMapping("/index")
    public String getProvince(@RequestParam(required = false) String provinceName, Model model) throws Exception{
        //获取省份
        List<Province> provinces = cityService.listProvince();
        Province province = null;
        for (Province province2 : provinces) {
            if (StringUtils.isNotBlank(provinceName)) {
                if(province2.getProvinceName().equals(provinceName)){
                    province = province2;
                    break;
                }
            }else if(province2.getCityName().equals("郑州")){
                province = province2;
                break;
            }
        }
        //获取天气
        WeatherResponse weather = weatherService.getDataByCityName(province.getCityName());
        //获取省份下的城市
        List<City> cities = cityService.listCity(province.getProvinceName());
        model.addAttribute("title","天气预报");
        model.addAttribute("provinceList",provinces);
        model.addAttribute("cityList",cities);
        model.addAttribute("cityName",province.getCityName());
        model.addAttribute("report",weather.getData());
        return StringUtils.isNotBlank(provinceName) == true ? "index::update_city":"index";
    }

    /**
     * 获取省份下城市列表
     * @param province
     * @return
     * @throws Exception
     */
    @GetMapping("/list/{province}")
    @ResponseBody
    public String getCityList(@PathVariable("province") String province) throws Exception {
        List<City> cities = cityService.listCity(province);
        return JSON.toJSONString(cities);
    }

}
